package com.example.demo.controller;

import com.example.demo.model.Klass;
import com.example.demo.service.KlassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("klass")
public class KlassController {
    @Autowired
    private KlassService klassService;

    public static Map<String, Klass> klasss = new HashMap<>();

    static {
        Klass s1 = new Klass("1", "tony");
        klasss.put(s1.getId(), s1);
        Klass s2 = new Klass("2", "jerry");
        klasss.put(s2.getId(), s2);
    }

    @RequestMapping("/search")
    public String search(ModelMap map, Klass klass) {
        if ("".equals(klass.getName())) {
            klass.setName(null);
        }
        if ("".equals(klass.getMajor())) {
            klass.setMajor(null);
        }
        List<Klass> klasss = klassService.findAll(klass);

        map.put("klassList", klasss);

        return "klass/list";
    }

    @RequestMapping("/list")
    public String list(ModelMap map, Klass klass) {
        if ("".equals(klass.getName())) {
            klass.setName(null);
        }
        if ("".equals(klass.getMajor())) {
            klass.setMajor(null);
        }
        map.put("klassList", klassService.findAll(klass));

        return "klass/list";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id) {
        klassService.deleteById(id);//数据库删除
        return "redirect:/klass/list";//重定向
    }

    @RequestMapping("create")
    public String create() {
        return "/klass/create";
    }

    @RequestMapping("save")
    public String save(Klass s) {
        if (s.getId() == null) {
            s.setId(UUID.randomUUID().toString());
            klassService.save(s);//数据库保存
        } else {
            klassService.update(s);
        }

        return "redirect:/klass/list";
    }

    @RequestMapping("update/{id}")
    public String update(@PathVariable String id, ModelMap map) {
        Klass s = klassService.getReferenceById(id);//数据库查询
        map.put("klass", s);
        return "/klass/update";
    }
}

